//
//  MAMemberMgrController.m
//  meiang_edu
//
//  Created by hfcb on 2018/9/9.
//  Copyright © 2018年 com.meiang.meiang_edu. All rights reserved.
//

#import "MAMemberMgrController.h"
#import "MAStaffCell.h"
#import "MAMgrPopView.h"
#import <zhPopupController.h>
#import "MAUserEditInfoController.h"
#import "MAStaffModel.h"
#import "MABabyRelationshipView.h"
#import "MALHJieSongTableController.h"
#import "MAAnPaiJieSongController.h"
#import "MAStaffInfoController.h"
#import "MABabyInfoViewController.h"
#import "MAFuncItemModel.h"

@interface MAMemberMgrController ()<UITableViewDelegate, UITableViewDataSource>
@property (weak, nonatomic) IBOutlet UIButton *leftBtn;
@property (weak, nonatomic) IBOutlet UIView *leftBtnIndicator;
@property (weak, nonatomic) IBOutlet UIButton *rightBtn;
@property (weak, nonatomic) IBOutlet UIView *rightBtnIndicator;
@property (weak, nonatomic) IBOutlet UITableView *myTableView;
/** bottomBtn */
@property(nonatomic,strong) UIButton *bottomBtn;

/** selectedBtn */
@property(nonatomic,weak) UIButton *selectedBtn;

/** enableModels */
@property(nonatomic,strong) NSMutableArray *enableModels;

/** disableModels */
@property(nonatomic,strong) NSMutableArray *disableModels;
/** view */
@property(nonatomic,strong) MABabyRelationshipView *rView;
/** popView */
@property(nonatomic,strong) MAMgrPopView *popView;

/** selectedIndexPath正在操作的indexpath */
@property(nonatomic,strong) NSIndexPath *selectedIndexPath;
@end

@implementation MAMemberMgrController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setupBasic];
    
    [self setupTableView];
}

- (void)setupBasic {
    self.leftBtn.selected = YES;
    self.leftBtnIndicator.hidden = NO;
    self.rightBtn.selected = NO;
    self.rightBtnIndicator.hidden = YES;
    
    self.navigationItem.rightBarButtonItem = [UIBarButtonItem itemWithTarget:self action:@selector(rightItemDidClick) image:@"reminderbutton_logo" highImage:@"reminderbutton_logo"];
    
    self.selectedBtn = self.leftBtn;
}

- (void)setupTableView {
    
    self.myTableView.tableHeaderView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 0, 4)];
    if (self.type == MAMemberMgrControllerTypeJieSong) {
        
        UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 58)];
//        view.backgroundColor = [UIColor redColor];
        [view addSubview:self.bottomBtn];
        self.myTableView.tableFooterView = view;
    }
    self.myTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.myTableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadData)];
    [self.myTableView.mj_header beginRefreshing];
//
//    self.myTableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(<#method#>)];
//    self.myTableView.mj_footer.hidden = YES;
}

- (void)rightItemDidClick {
    DLog(@"");
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self hiddenTabbar:YES];
    [self.myTableView reloadData];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)loadData {
    
    MAUserInfo *userinfo = [MAUserInfoTool userinfo];
    //    if (!userinfo.token) {
    //        [MBManager showBriefAlert:@"登录状态已过期,请重新登录"];
    //        return;
    //    }
    [MBManager showLoading];
    DLog(@"%@",self.title);
    [ZBRequestManager requestWithConfig:^(ZBURLRequest *request) {
        request.requestSerializerType = ZBHTTPRequestSerializer;
        request.URLString = [NSString stringWithFormat:@"%@%@?entity_type=%@&status=%ld",BASE_LISTENTITY_LIST,self.jigou_id, self.funcItemModel.function_code, self.selectedBtn.tag];
        request.methodType = ZBMethodTypeGET;
        [request setValue:userinfo.token forHeaderField:@"token"];
        request.apiType = ZBRequestTypeRefresh;
    } success:^(id responseObject, apiType type) {
        [MBManager hideAlert];
        // 解析数据
        NSDictionary *dataDict = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        DLog(@"%@",dataDict);
        NSInteger code = [dataDict[@"msgcode"] integerValue];
        if (code == 1) { // 请求成功
            [MBManager hideAlert];
            if (self.selectedBtn) {
                self.enableModels = [MAStaffModel mj_objectArrayWithKeyValuesArray:dataDict[@"value"]];
            } else {
                self.disableModels = [MAStaffModel mj_objectArrayWithKeyValuesArray:dataDict[@"value"]];
            }
            [self.myTableView reloadData];
        } else {
            [MBManager showBriefAlert:dataDict[@"message"]];
        }
    } failure:^(NSError *error) {
        DLog(@"%@",error);
        
    } finished:^(id responseObject, apiType type, NSError *error, BOOL isCache) {
        if (isCache==YES) {
            DLog(@"使用了缓存");
        }
        [self.myTableView.mj_header endRefreshing];
    }];
}

- (IBAction)leftBtnDidClick {
    self.rightBtn.selected = NO;
    self.rightBtnIndicator.hidden = YES;
    self.leftBtn.selected = YES;
    self.leftBtnIndicator.hidden = NO;
    self.selectedBtn = self.leftBtn;
    [self.myTableView.mj_header beginRefreshing];
}

- (IBAction)rightBtnDidClick {
    self.leftBtn.selected = NO;
    self.leftBtnIndicator.hidden = YES;
    self.rightBtn.selected = YES;
    self.rightBtnIndicator.hidden = NO;
    self.selectedBtn = self.rightBtn;
    [self.myTableView.mj_header beginRefreshing];
}
- (void)bottomBtnDidClick {
    DLog(@"");
    MALHJieSongTableController *vc = [[UIStoryboard storyboardWithName:NSStringFromClass([MALHJieSongTableController class]) bundle:nil] instantiateInitialViewController];
    vc.title = @"临时接送人";
    vc.jigouModel = self.jigouModel;
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark - UITableViewDelegate, UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.selectedBtn.tag ? self.enableModels.count : self.disableModels.count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 64;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSInteger row = indexPath.row;
    UITableViewCell *cell;
    
    MAStaffModel *model = self.selectedBtn.tag ? self.enableModels[row] : self.disableModels[row];
    MAStaffCell *staffCell = [MAStaffCell cellWithTableView:tableView];
    staffCell.cellStyle = MAStaffCellStyleMgrList;
    staffCell.model = model;
    cell = staffCell;
    
    UILongPressGestureRecognizer * longPressGesture = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(cellLongPress:)];
    
    longPressGesture.minimumPressDuration = 1.0f;//设置长按 时间
    [cell addGestureRecognizer:longPressGesture];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    NSInteger row = indexPath.row;
    MAStaffModel *model = self.selectedBtn.tag ? self.enableModels[row] : self.disableModels[row];
    switch (self.type) {
        case MAMemberMgrControllerTypeBaby: { // 跳宝宝详情
            MABabyInfoViewController *vc = [[MABabyInfoViewController alloc] init];
            vc.model = model;
            [self.navigationController pushViewController:vc animated:YES];
            break;
        }
        case MAMemberMgrControllerTypeFamily: { // 跳转家庭成员详情
            MAStaffInfoController *vc = [[UIStoryboard storyboardWithName:NSStringFromClass([MAStaffInfoController class]) bundle:nil] instantiateInitialViewController];
            vc.staffModel = model;
            [self.navigationController pushViewController:vc animated:YES];
            break;
        }
        case MAMemberMgrControllerTypeJieSong: { // 跳安排接送
            MAAnPaiJieSongController *vc = [[UIStoryboard storyboardWithName:NSStringFromClass([MAAnPaiJieSongController class]) bundle:nil] instantiateInitialViewController];
            vc.title = @"安排接送";
            vc.jigou_id = self.jigou_id;
            vc.jigouModel = self.jigouModel;
            vc.model = model;
            [self.navigationController pushViewController:vc animated:YES];
            break;
        }
        case MAMemberMgrControllerTypeUserMgr: { // 跳转用户详情
            MAStaffInfoController *vc = [[UIStoryboard storyboardWithName:NSStringFromClass([MAStaffInfoController class]) bundle:nil] instantiateInitialViewController];
            vc.staffModel = model;
            [self.navigationController pushViewController:vc animated:YES];
            break;
        }
            
        default:
            break;
    }
}

- (void)cellLongPress:(UILongPressGestureRecognizer *)longRecognizer{
    if (longRecognizer.state == UIGestureRecognizerStateBegan) {
        //成为第一响应者，需重写该方法
        [self becomeFirstResponder];
        
        CGPoint location = [longRecognizer locationInView:self.myTableView];
        NSIndexPath * indexPath = [self.myTableView indexPathForRowAtPoint:location];
        self.selectedIndexPath = indexPath;
        //可以得到此时你点击的哪一行
        
        //在此添加你想要完成的功能
        DLog(@"");
        NSMutableArray *titleArr = [NSMutableArray array];
        switch (self.type) {
            case MAMemberMgrControllerTypeFamily: {
                if (self.leftBtn.isSelected) { // 左按钮
                    titleArr = [@[@"停用当前卡片", @"当前卡片与宝宝关系"] mutableCopy];
                } else {
                    titleArr = [@[@"启用当前卡片", @"移出当前卡片"] mutableCopy];
                }
                break;
            }
            case MAMemberMgrControllerTypeBaby: {
                if (self.leftBtn.isSelected) { // 左按钮
                    titleArr = [@[@"停用当前卡片"] mutableCopy];
                } else {
                    titleArr = [@[@"启用当前卡片", @"移出当前卡片"] mutableCopy];
                }
                break;
            }
            case MAMemberMgrControllerTypeJieSong: {
                if (self.leftBtn.isSelected) { // 左按钮
                    titleArr = [@[@"停用当前卡片", @"当前卡片与宝宝关系"] mutableCopy];
                } else {
                    titleArr = [@[@"启用当前卡片", @"移出当前卡片"] mutableCopy];
                }
                break;
            }
            case MAMemberMgrControllerTypeUserMgr: {
                if (self.leftBtn.isSelected) { // 左按钮
                    titleArr = [@[@"停用当前卡片", @"当前卡片与宝宝关系"] mutableCopy];
                } else {
                    titleArr = [@[@"启用当前卡片", @"移出当前卡片"] mutableCopy];
                }
                break;
            }
            default:
                break;
        }
        
        MAMgrPopView *popView = [MAMgrPopView popViewWithTitles:titleArr clickBlock:^(NSInteger clickIdx) {
            DLog(@"============%ld",clickIdx);
            if (self.type == MAMemberMgrControllerTypeJieSong || self.type == MAMemberMgrControllerTypeFamily || self.type == MAMemberMgrControllerTypeUserMgr) {
                if (self.leftBtn.isSelected) { // 启用的列表
                    if (clickIdx == 0) { // 停用当前
                        [self requestEnableOrDisable:NO indexPath:indexPath];
                    } else { // 编辑关系
                        [self.zh_popupController dismiss];
                        MABabyRelationshipView *view = [MABabyRelationshipView babyRelationshipView];
                        [view cancelBtnAddTarget:self action:@selector(dismissView)];
                        [view okBtnAddTarget:self action:@selector(popViewOKBtnClick)];
                        view.layer.cornerRadius = 10;
                        view.layer.masksToBounds = YES;
                        self.rView = view;
                        self.zh_popupController = [[zhPopupController alloc] init];
                        self.zh_popupController.dismissOnMaskTouched = YES;
                        self.zh_popupController.dismissOppositeDirection = YES;
                        self.zh_popupController.slideStyle = zhPopupSlideStyleShrinkInOut2;
                        [self.zh_popupController presentContentView:view duration:0.35 springAnimated:YES];
                    }
                } else { // 停用的列表
                    if (clickIdx == 0) { // 启用当前
                        [self requestEnableOrDisable:YES indexPath:indexPath];
                    } else { // 移出当前
                        
                    }
                }
            }
            if (self.type == MAMemberMgrControllerTypeBaby) {
                if (self.leftBtn.isSelected) { // 启用的列表
                    if (clickIdx == 0) { // 停用当前
                        [self requestEnableOrDisable:NO indexPath:indexPath];
                    } else { // 编辑关系
                        
                    }
                } else { // 停用的列表
                    if (clickIdx == 0) { // 启用当前
                        [self requestEnableOrDisable:YES indexPath:indexPath];
                    } else { // 移出当前
                        
                    }
                }
            }
            [self.zh_popupController dismiss];
        }];
        popView.layer.cornerRadius = 10;
        popView.layer.masksToBounds = YES;
        self.zh_popupController = [[zhPopupController alloc] init];
        self.zh_popupController.dismissOnMaskTouched = YES;
        self.zh_popupController.dismissOppositeDirection = YES;
        self.zh_popupController.slideStyle = zhPopupSlideStyleShrinkInOut2;
        [self.zh_popupController presentContentView:popView duration:0.35 springAnimated:YES];
    }
}

- (void)dismissView {
    DLog(@"");
    [self.zh_popupController dismiss];
}
- (void)popViewOKBtnClick {
    DLog(@"");
    NSString *input = self.rView.nameTF.text;
    if (!input.length) {
        [MBManager showBriefAlert:@"输入信息不能为空"];
        return;
    }
    MAStaffModel *model = self.enableModels[self.selectedIndexPath.row];
    NSString *url = BASE_ENTITY_ADD;
    NSDictionary *params = @{@"funcode" : @"family_sender", @"entity_type" : @"user", @"entitykey" : model.keyid, @"orgkey" : model.orgkey, @"relation" : input};
    
    [self requestWithUrl:url params:[params mutableCopy] indexPath:nil];
}

/**
 停用或启用
 
 @param enable yes=启用  no=停用
 @param indexPath 被点击cell的indexpath
 */
- (void)requestEnableOrDisable:(BOOL)enable indexPath:(NSIndexPath *)indexPath {
    MAUserInfo *userinfo = [MAUserInfoTool userinfo];
    //    if (!userinfo.token) {
    //        [MBManager showBriefAlert:@"登录状态已过期,请重新登录"];
    //        return;
    //    }
    [MBManager showLoading];
    MAStaffModel *model = enable ? self.disableModels[indexPath.row] : self.enableModels[indexPath.row];
    NSString *url = enable ? BASE_LIST_ENABLE : BASE_LIST_DISABLE;
    NSDictionary *body = @{@"entity_type" : model.entity_type, @"entity_id" : model.keyid, @"org_id" : model.orgkey};
    
    NSError *error;
    
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:body options:0 error:&error];
    
    NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    
    AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
    
    NSMutableURLRequest *req = [[AFJSONRequestSerializer serializer] requestWithMethod:@"POST" URLString:url parameters:nil error:nil];
    
    [req setValue:@"application/text" forHTTPHeaderField:@"Content-Type"];
    
    [req setValue:@"application/json" forHTTPHeaderField:@"Accept"];
    
    [req setHTTPBody:[jsonString dataUsingEncoding:NSUTF8StringEncoding]];
    
    [[manager dataTaskWithRequest:req completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {
        [MBManager hideAlert];
        if (!error) {
            DLog(@"Reply JSON: %@", responseObject);
            NSInteger msgcode = [responseObject[@"msgcode"] integerValue];
            NSString *message = responseObject[@"message"];
            if (msgcode == 1) {
                [MBManager showBriefAlert:message];
                if (enable) {
                    [self.disableModels removeObject:model];
                    [self.enableModels addObject:model];
                } else {
                    [self.enableModels removeObject:model];
                    [self.disableModels addObject:model];
                }
                [self.myTableView reloadData];
            } else {
                [MBManager showBriefAlert:message];
            }
        } else {
            DLog(@"Error: %@, %@, %@", error, response, responseObject);
            [MBManager showBriefAlert:@"网络错误"];
        }
    }] resume];
}


/**
 请求网络数据

 @param url 请求地址
 @param params 请求参数
 @param indexPath <#indexPath description#>
 */
- (void)requestWithUrl:(NSString *)url params:(NSMutableDictionary *)params indexPath:(NSIndexPath *)indexPath {
    MAUserInfo *userinfo = [MAUserInfoTool userinfo];
    //    if (!userinfo.token) {
    //        [MBManager showBriefAlert:@"登录状态已过期,请重新登录"];
    //        return;
    //    }
    [MBManager showLoading];
    MAStaffModel *model = [url isEqualToString:BASE_ENTITY_ADD] ? self.enableModels[indexPath.row] : self.disableModels[indexPath.row];
    
    NSError *error;
    
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:params options:0 error:&error];
    
    NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    
    AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
    
    NSMutableURLRequest *req = [[AFJSONRequestSerializer serializer] requestWithMethod:@"POST" URLString:url parameters:nil error:nil];
    
    [req setValue:@"application/text" forHTTPHeaderField:@"Content-Type"];
    
    [req setValue:@"application/json" forHTTPHeaderField:@"Accept"];
    
    [req setHTTPBody:[jsonString dataUsingEncoding:NSUTF8StringEncoding]];
    
    [[manager dataTaskWithRequest:req completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {
        [MBManager hideAlert];
        if (!error) {
            DLog(@"Reply JSON: %@", responseObject);
            NSInteger msgcode = [responseObject[@"msgcode"] integerValue];
            NSString *message = responseObject[@"message"];
            if (msgcode == 1) {
                [MBManager showBriefAlert:message];
                if ([url isEqualToString:BASE_ENTITY_ADD]) { // 添加关系
                    [self.zh_popupController dismiss];
                    [self.myTableView.mj_header beginRefreshing];
                } else if ([url isEqualToString:BASE_LIST_DELETE]) { // 删除
                    [self.disableModels removeObject:model];
                } else { //
                }
                [self.myTableView reloadData];
            } else {
                [MBManager showBriefAlert:message];
            }
        } else {
            DLog(@"Error: %@, %@, %@", error, response, responseObject);
            [MBManager showBriefAlert:@"网络错误"];
        }
    }] resume];
}
- (BOOL)canBecomeFirstResponder{
    return YES;
}

- (UIButton *)bottomBtn {
    if (_bottomBtn == nil) {
        _bottomBtn = [[UIButton alloc] init];
        _bottomBtn.width = SCREEN_WIDTH - 8;
        _bottomBtn.height = 50;
        _bottomBtn.x = 4;
        _bottomBtn.y = 4;
        [_bottomBtn addTarget:self action:@selector(bottomBtnDidClick) forControlEvents:UIControlEventTouchUpInside];
        _bottomBtn.backgroundColor = PROJECT_DEFAULT_COLOR;
        [_bottomBtn setTitle:@"添加临时接送人" forState:UIControlStateNormal];
        _bottomBtn.titleLabel.textColor = [UIColor whiteColor];
        _bottomBtn.layer.cornerRadius = 5;
        _bottomBtn.layer.masksToBounds = YES;
    }
    return _bottomBtn;
}

#pragma mark - getter & setter
- (NSMutableArray *)enableModels {
    if (_enableModels == nil) {
        _enableModels = [NSMutableArray array];
    }
    return _enableModels;
}
- (NSMutableArray *)disableModels {
    if (_disableModels == nil) {
        _disableModels = [NSMutableArray array];
    }
    return _disableModels;
}
@end
